(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.dataInquiry.updateController', updateController);
	updateController.$inject = [ '$scope', 'Constants', 'modalService', 'gridService', 'layoutConfig', 'validatorConfig', 'authService',
			'dataInquiryService' ];
	function updateController($scope, Constants, modalService, gridService, layoutConfig, validatorConfig, authService, dataInquiryService) {
		var ctrl = this, dataInquiryInfo = $scope.$stateParams.params, errorMessage = {};
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.dataInquiry = {};
		ctrl.dataInquiry.paramList = ctrl.dataInquiry.paramList || [];

		ctrl.serviceCodeOptions = {};
		ctrl.dinqFilebuilderIdOptions = {};
		ctrl.parmTypeOptions = {};
		
		ctrl.init = function() {
			var params = {
				dinquiryId : dataInquiryInfo.dinquiryId
			};
			if(ctrl.validatorConfig) ctrl.layoutConfig.formConfigs.params.tableConfigs.table.validatorConfig = ctrl.validatorConfig.paramList;
			ctrl.innerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.params.tableConfigs.table, rowSelectionChanged);
			ctrl.innerGridOptions.data = 'vm.dataInquiry.paramList';
			ctrl.innerGridOptions.enableRowHeaderSelection = false;
			authService.update(params).then(function(response) {
				ctrl.dataInquiry = response.data || dataInquiryInfo;
				ctrl.dataInquiry.paramList = ctrl.dataInquiry.paramList || [];
				angular.extend(ctrl.serviceCodeOptions,  response.data.services);
				angular.extend(ctrl.dinqFilebuilderIdOptions,  response.data.dataInquiryBuilders);
				angular.extend(ctrl.parmTypeOptions,  response.data.dataTypes);
			});
		};
		
		ctrl.initAccessTypeListOption = function(models, option){
			angular.forEach(ctrl.dataInquiry.inquiryAccess, function(obj){
				var item = {
					"label" : obj.dinqAccessType + " - " + obj.dinqAccessDesc,
					"value" : obj.dinqAccessType
				};
				option.data.push(item);
			});
		};
		
		ctrl.setAccessTypeList = function(result, option){
			if(!ctrl.dataInquiry.accessTypeList){
				ctrl.dataInquiry.accessTypeList = [];
			}
			if(result && angular.isArray(result)){
				angular.forEach(result, function(obj){
					var item = {
						"label" : obj.dinqAccessType + " - " + obj.dinqAccessDesc,
						"value" : obj.dinqAccessType
					};
					option.data.push(item);
					ctrl.dataInquiry.accessTypeList.push(obj.dinqAccessType);
				});
			}
		};

		//set useGlobalValue according sqlScript's tableName contains 'G' orNot 
		ctrl.setUseGlobalValue = function(){
			ctrl.dataInquiry.sqlScript = ctrl.dataInquiry.sqlScript;
			if (ctrl.dataInquiry.sqlScript != null){
				var parm = ctrl.dataInquiry.sqlScript.toString();
				if (parm.indexOf('_G_')!= -1){
					ctrl.dataInquiry.useGlobalDb = 'Y';
				} else {
					ctrl.dataInquiry.useGlobalDb = 'N';
				}
			}
		};
		
		/**
		 * check if sql script has one DML statement
		 * @param sqlScript. textarea value for SQL Script
		 */
		ctrl.checkDmlStatement = function (sqlScript) {
			var dmlActions = ['select'];
			if (!sqlScript) return true;
			var bValid = true;
			var numSql = sqlScript.split('\r\n').length;
			if (numSql > 1) bValid = false;
			if (bValid) {
				var sqlItem = sqlScript.trim();
				var firstWord = (sqlItem.indexOf(' ') == -1)
								? sqlItem
								: sqlItem.substring(0, sqlItem.indexOf(' '));
				// it is like ',select,'.
				var allDmlActions = "," + dmlActions.toString() + ",";
				// it means first word in sql script must be included into dmlActions
				if (allDmlActions.indexOf("," + firstWord.toLowerCase() + ",") == -1) {
					bValid = false;
				}
			}
			if (!bValid) {
				modalService.openErrorDialogs({
					'messages' : [ 'js.cda.dataInquiry.sqlScript.select-stmt-required' ]
				});
			}
			return bValid;
		};
		
		//select ${} from sqlScript
		ctrl.filter = function (string) {
			var subParm;
			if (string != null){
				var m = string.indexOf('{');
				var n = string.indexOf('}');
				if ( m != -1){
					subParm = string.substring(m+1, n);
					ctrl.parms.push(subParm);
					if (string.length >= n){						
						string = string.substring(n +1, string.length);
						ctrl.filter(string);
					}
				}
			}
			return ctrl.filterRecopy(ctrl.parms);
		};
		
		//filter recopy
		ctrl.filterRecopy = function (parms){
			ctrl.parmsCopy = [];
			for (var i=0; i< parms.length; i++){
				if (ctrl.parmsCopy.indexOf(parms[i]) == -1){
					ctrl.parmsCopy.push(parms[i]);
				};
			};
			return ctrl.parmsCopy;
		};
		
		ctrl.updateSave = function() {
			var i = 0;
			//clear
			ctrl.parms = [];
			ctrl.parmsCopy = [];
			ctrl.dataInquiry.sqlScript = ctrl.dataInquiry.sqlScript;
			if (ctrl.dataInquiry.sqlScript != null){
				var parm = ctrl.dataInquiry.sqlScript.toString();
				var dmlStatementValid = ctrl.checkDmlStatement(parm);
				if ( dmlStatementValid) {		//only selete dmlStatement is allowed
					var parms = ctrl.filter(parm);
					ctrl.dataInquiry.paramList = ctrl.dataInquiry.paramList || [];
					if (ctrl.dataInquiry.paramList && ctrl.dataInquiry.paramList.length === parms.length){	
						angular.forEach( parms, function (pValue){				
							angular.forEach(ctrl.dataInquiry.paramList, function (value, key){
								if (value ){
									if ( value.parmName === pValue){							
										i ++;
										value.parmName = pValue;
										value.dinquiryParmId = value.dinquiryParmId;
										value.parmType = value.parmType;
										value.parmMaxLen = value.parmMaxLen;
										value.parmDesc = value.parmDesc;
									}
								} else {
									modalService.openErrorDialogs({
										'messages' : [ "js.pub.error.params-unused" + value.parmName]
									});
								}
							});
						});
						if ( i === parms.length ){
							if (ctrl.dataInquiry.taskId) {
								return authService.updateContinueSave(ctrl.dataInquiry).then(saveSuccessful, saveFailed);
							} else {
								return authService.updateSave(ctrl.dataInquiry).then(saveSuccessful, saveFailed);
							}
						} else {
							modalService.openErrorDialogs({
								'messages' : [ 'js.pub.error.params-undefined']
							});
						}
					} else {
						modalService.openErrorDialogs({
							'messages' : [ 'js.pub.error.params-doesnot equals to sql script in need' + parms ]
						});
					}
				}
			}
		};

		ctrl.updateSubmit = function() {
			var i = 0;
			//clear
			ctrl.parms = [];
			ctrl.parmsCopy = [];
			ctrl.dataInquiry.sqlScript = ctrl.dataInquiry.sqlScript;
			if (ctrl.dataInquiry.sqlScript != null){
				var parm = ctrl.dataInquiry.sqlScript.toString();
				var dmlStatementValid = ctrl.checkDmlStatement(parm);
				if ( dmlStatementValid) {		//only selete dmlStatement is allowed
					var parms = ctrl.filter(parm);
					ctrl.dataInquiry.paramList = ctrl.dataInquiry.paramList || [];
					if (ctrl.dataInquiry.paramList && ctrl.dataInquiry.paramList.length === parms.length){	
						angular.forEach( parms, function (pValue){				
							angular.forEach(ctrl.dataInquiry.paramList, function (value, key){
								if (value ){
									if ( value.parmName === pValue){							
										i ++;
										value.parmName = pValue;
										value.dinquiryParmId = value.dinquiryParmId;
										value.parmType = value.parmType;
										value.parmMaxLen = value.parmMaxLen;
										value.parmDesc = value.parmDesc;
									}
								} else {
									modalService.openErrorDialogs({
										'messages' : [ "js.pub.error.params-unused" + value.parmName]
									});
								}
							});
						});
						if ( i === parms.length ){
							if (ctrl.dataInquiry.taskId) {
								return authService.updateContinueSubmit(ctrl.dataInquiry).then(submitSuccessful, submitFailed);
							} else {
								return authService.updateSubmit(ctrl.dataInquiry).then(submitSuccessful, submitFailed);
							}
						} else {
							modalService.openErrorDialogs({
								'messages' : [ 'js.pub.error.params-undefined']
							});
						}
					} else {
						modalService.openErrorDialogs({
							'messages' : [ 'js.pub.error.params-doesnot equals to sql script in need' + parms ]
						});
					}
				} 
			}
		};

		function rowSelectionChanged(eventRow, selectedRows) {
			ctrl.selectedParamList = selectedRows;
		}

		function submitSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'title.dialog.successful.submit' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('cda.dataInquiry.list');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'cda.workflow.wfSetup.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.datainquiry.list',
					'state' : 'cda.dataInquiry.list',
					'params' : {}
				}]
			});
		}

		function submitFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}

		function saveSuccessful(response) {
			modalService.openInfoDialogs({
				'messages' : [ 'title.dialog.successful.save' ]
			});
			if (response.data.task && response.data.task.taskId) {
				authService.saveSuccessfulProcess(response.data.task).then(function(response) {
					var routerInfo = response.data || {}, state = routerInfo.processState;
					delete routerInfo.processState;
					$scope.go(state, routerInfo);
				}, angular.noop);
			}
		}

		function saveFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
	}
})(angular);